package com.github.od.filter;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.github.od.constants.CommonConstants;
import com.github.od.exception.auth.ClientInvalidException;
import com.github.od.rpc.ClientAuthRpc;
import com.github.od.util.JWTUtil;
import com.github.od.util.jwt.IJWTInfo;
import com.github.od.vo.BaseResponse;
import com.github.od.vo.ObjectRestResponse;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
 * 权限校验过滤器
 * 
 * @author xieweikun
 * @version 2017年11月17日 上午11:35:54
 */
@Component
public class AccessFilter extends ZuulFilter {

	@Autowired
	private JWTUtil jwtUtil;
	@Autowired
	private ClientAuthRpc clientAuthRpc;
	
	
	@Value("${client.token-header}")
	private String clientTokenHeader;
	@Value("${client.id}")
	private String clientId;
	@Value("${client.secret}")
	private String secret;
	

	@Override
	public Object run() {
		// 做校验
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest(); // 获取当前请求
		// 如果是申请密钥或者刷新密钥时，就不过滤
		if (request.getRequestURI().substring("/api".length()).startsWith("/auth/jwt")) {
			return null;
		}
		String accessToken = request.getHeader("access-token"); // 获取当前token
		try {
			// 验证用户合法性
			IJWTInfo ijwtInfo = jwtUtil.getInfoFromToken(accessToken);
			// TODO 用户权限
			// 申请客户端密钥头部
			BaseResponse resp = clientAuthRpc.getAccessToken(clientId, secret);
			if (resp.getStatus() == 200) {
				ObjectRestResponse<String> clientToken = (ObjectRestResponse<String>) resp;
				requestContext.addZuulRequestHeader(clientTokenHeader, clientToken.getData());
			}else {
				throw new ClientInvalidException("Auth client secret is Error!");
			}
		} catch(ClientInvalidException ex) {
			requestContext.setResponseBody(JSON.toJSONString(
					new BaseResponse(ex.getStatus(), ex.getMessage())));
			ex.printStackTrace();
		} catch (Exception e) {
			requestContext.setResponseBody(JSON.toJSONString(
					new BaseResponse(CommonConstants.EX_TOKEN_ERROR_CODE, "Token Error or Token is Expired!")));
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public String filterType() {
		// 前置的
		return "pre";
	}

}
